<template>
  <check-file ref="RefFile" />
  <a-spin :spinning="spinning" tip="正在进入面试界面，请稍后...">
    <div class="goback">
      <GoBack />
    </div>
    <div class="title">{{ title }}正在进行中……</div>
    <div v-if="signUserList.length === 0">
      <!-- 没有用户签到的页面 -->
      <not-data-page @refreshData="refreshData" />
    </div>
    <template v-else>
      <div class="score">
        <div class="interview">
          <a-card class="interview__info">
            <a-avatar :size="120" :src="userInfo.avatar_url" class="interview__info__wxavatar" />
            <p class="interview__info__wxname">{{ userInfo.nick_name }}</p>
            <div class="interview__info__item"><span style="font-weight: bold">姓名：</span>{{ userInfo.name }}</div>
            <div class="interview__info__item"><span style="font-weight: bold">班级：</span>{{ userInfo.class_name }}</div>
            <div class="interview__info__item"><span style="font-weight: bold">手机号：</span>{{ userInfo.phone }}</div>
            <div class="interview__info__item">
              <a-button type="link" style="font-weight: bold; font-size: 16px" @click="openPreview" :disabled="signResume ? false : true">查看简历</a-button>
            </div>
          </a-card>
          <div class="interview__button">
            <a-button size="large" type="primary" danger style="margin: 5px 5px 15px 5px; width: 96%" block @click="goScore" :disabled="isToScore ? true : false">打 分</a-button>
            <a-button size="large" style="width: 96%" block @click="callNext" :disabled="current === signUserList.length - 1 ? true : false">下一位</a-button>
          </div>
        </div>
        <!-- 问卷部分 -->
        <a-card class="paper" title="报名答卷">
          <div class="questionWrap" v-if="paperAnswerData?.id">
            <div class="question" v-for="(answer, index) in paperAnswerData?.answers" :key="index">
              <div class="question__title">
                {{ answer?.number }}.
                {{ answer?.question_title }}
                <span style="color: #999; font-size: 13px">
                  <span v-if="answer?.question_type === 1">[单选题]</span>
                  <span v-else-if="answer?.question_type === 2">[多选题]</span>
                  <span v-else>[填空题]</span>
                </span>
              </div>
              <div class="question__answer">
                {{ answer?.answer_content[0] }}
              </div>
            </div>
          </div>
          <div v-else style="color: red">没有答卷</div>
        </a-card>
      </div>
    </template>
  </a-spin>
  <go-score ref="openModal" :app_user_id="signUserList[current]" @changeBtnStatus="changeBtnStatus" />
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, Ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import GoScore from './GoScore.vue'
import NotDataPage from '../../../components/NotDataPage.vue'
import GoBack from '../../../components/goback.vue'
import CheckFile from '../../../components/CheckFile.vue'
import { get, post } from '../../../utils/request/request'
import { message, notification } from 'ant-design-vue'

interface SignUserList {
  app_user_id: number
  number: number
  name: string
  class_name: string
  status: number
}

interface UserInfo {
  id: number | undefined
  nick_name: string
  name: string
  class_name: string
  phone: string
  app_id: string
  avatar_url: string
  resume_url: string
  paper_count: number
}

interface PaperAnswerData {
  id: number | undefined
  title: string
  user_id: number | undefined
  user_name: string
  user_class: string
  answer_time: string
  answers: {
    number: number
    question_title: string
    is_require: boolean
    question_type: number
    answer_content: string[]
  }[]
}

const spinning = ref(true)

// 签到用户数据
const signUserList = ref<number[]>([])
const signResume = ref<string>('')

// 当前用户个人信息数据
const userInfo: Ref<UserInfo> = ref({
  id: undefined, //问卷id
  nick_name: '', //微信昵称
  name: '', //姓名
  class_name: '', //班级
  phone: '', //手机号
  app_id: '', //小程序用户id
  avatar_url: '', //头像url
  resume_url: '', //简历链接
  paper_count: 0 //问卷数
})

//答卷数据
const paperAnswerData: Ref<PaperAnswerData> = ref({
  id: undefined, //问卷id
  title: '', //问卷标题
  user_id: undefined, //用户id
  user_name: '', //用户姓名
  user_class: '', //用户班级
  answer_time: '', //回答时间
  answers: []
})

// 和路由相关
const useRouteEffect = () => {
  const route = useRoute()
  const title = ref<string>('')
  const id = ref<string>('')
  const getRouteParameters = () => {
    id.value = route.params.id as string
    // title.value = route.params.title as string;
  }
  return { getRouteParameters, id, title }
}

//emit事件
const useEmitEffect = (token: string, id: string) => {
  const { getsignUserList } = useHttpEffect(token)
  const refreshData = () => {
    getsignUserList(id)
  }
  return { refreshData }
}

// 网络请求
const useHttpEffect = (token: string) => {
  const getsignUserList = async (id: string) => {
    const res: any = await get(`/admin/api/v1/recruitment/interview/batch/${id}/users/sign?page=1&limit=1000`, token)
    console.log(res)
    if (res?.status_code === 0) {
      if (res?.data == null) {
        message.info('没有签到的用户')
        spinning.value = false
      } else {
        // signUserList.value = res.data;
        // @ts-ignore
        res.data.forEach((user) => {
          if (user.status != 2) {
            signUserList.value.push(user.app_user_id)
          }
        })
      }
    }
  }
  const getUserDetail = async (current: number) => {
    const res: any = await get(`/admin/api/v1/user/${current}`, token)
    console.log(res)
    if (res?.status_code === 0) {
      userInfo.value = res?.data
      signResume.value = res?.data?.resume_url
    }
    spinning.value = false
  }
  const getPaperAnswerData = async (id: string, current: number) => {
    const res: any = await get(`/admin/api/v1/paper/${id}/answers?user=${current}`, token)
    console.log('getPaperAnswerData', res)
    if (res?.status_code === 0) {
      paperAnswerData.value = res?.data
    }
  }
  // 叫号
  const postToCall = async (id: string, next: number, current: Ref<number>) => {
    const res: any = await post(
      `/admin/api/v1/recruitment/interview/batch/${id}/call`,
      {
        app_user_id: next
      },
      token
    )
    console.log(res)
    if (res?.status_code === 0 && res?.status_msg === 'ok') {
      console.log(9)
      message.success('叫号成功，下一位')
      current.value++
    }
  }
  return { getsignUserList, getUserDetail, getPaperAnswerData, postToCall }
}

// 用户相关操作
const useBtnEffect = (id: string, token: string) => {
  const current = ref<number>(0)
  const { postToCall } = useHttpEffect(token)
  // 打分
  const openModal = ref()
  const isToScore = ref<boolean>(false)
  const goScore = () => {
    openModal.value.showModal()
  }
  const changeBtnStatus = (status: boolean) => {
    isToScore.value = status
  }
  //叫号
  const callNext = () => {
    postToCall(id, current.value + 1, current)
  }
  //查看简历
  const RefFile = ref()
  const openPreview = () => {
    RefFile.value.pdfPreview(signResume.value)
  }
  return {
    current,
    openModal,
    isToScore,
    goScore,
    changeBtnStatus,
    callNext,
    RefFile,
    openPreview
  }
}

export default defineComponent({
  components: {
    GoScore,
    NotDataPage,
    GoBack,
    CheckFile
  },
  setup() {
    const token: string = localStorage.getItem('token') as string
    const { getRouteParameters, id, title } = useRouteEffect()
    getRouteParameters()
    const { current, openModal, isToScore, goScore, changeBtnStatus, callNext, RefFile, openPreview } = useBtnEffect(id.value, token)
    const { getsignUserList, getUserDetail, getPaperAnswerData } = useHttpEffect(token)
    const { refreshData } = useEmitEffect(token, id.value)

    watch(current, (newVal, oldVal) => {
      // console.log("watch", newVal, oldVal);
      setTimeout(() => {
        getUserDetail(signUserList.value[newVal])
        getPaperAnswerData(id.value, signUserList.value[newVal])
      }, 1000)
      if (newVal === signUserList.value.length - 1) {
        // message.success("本场面试最后一个同学", 0);
        notification['success']({
          message: '本场面试最后一个同学'
        })
      }
    })

    onMounted(async () => {
      await getRouteParameters()
      await getsignUserList(id.value)
      if (signUserList.value.length > 0) {
        getUserDetail(signUserList.value[current.value])
        getPaperAnswerData(id.value, signUserList.value[current.value])
      }
    })

    return {
      signResume,
      spinning,
      signUserList,
      userInfo,
      paperAnswerData,
      title,
      current,
      openModal,
      isToScore,
      goScore,
      changeBtnStatus,
      callNext,
      RefFile,
      openPreview,
      refreshData
    }
  }
})
</script>

<style lang="less" scoped>
.goback {
  top: 115px;
  left: 285px;
  width: 100%;
  position: fixed;
}
.title {
  text-align: center;
  font-size: 30px;
  font-weight: bold;
  padding: 30px 0;
  color: #333;
}
.score {
  display: flex;
  .interview {
    flex: 1;
    min-width: 350px;
    padding: 10px 20px;
    &__button {
      padding: 13px 0;
      text-align: center;
      &__title {
        font-size: 20px;
      }
    }
    &__info {
      text-align: center;
      &__wxavatar {
        margin-top: 10px;
      }
      &__wxname {
        text-align: center;
        font-weight: bold;
        font-size: 22px;
        padding: 6px 0 15px 0;
      }
      &__other {
        vertical-align: middle;
      }
      &__item {
        font-size: 16px;
        padding: 2px;
      }
    }
  }
  .paper {
    flex: 3;
    margin: 10px 20px;
    border: 1px solid #c8c8c8;
    border-radius: 2px;
  }
}
.questionWrap {
  overflow: auto;
  height: 52vh;
}
.top {
  &__title {
    font-size: 24px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 5px;
  }
  &__time {
    text-align: center;
    color: #999;
    border-bottom: 1px solid #c8c8c8;
    margin: 5px;
  }
}
.question {
  padding: 5px 0;
  &__title {
    font-size: 20px;
  }
  &__answer {
    font-size: 16px;
    color: red;
    font-weight: bold;
    padding: 5px 20px;
  }
}
</style>
